package com.jquest.input;

import org.newdawn.slick.Input;
import com.jquest.data.AbstractEntity;
import com.jquest.data.Map;
import com.jquest.Demo;

/**
 * Created by IntelliJ IDEA.
 * User: Johan
 * Date: 2009-dec-11
 * Time: 04:19:55
 * To change this template use File | Settings | File Templates.
 */
public class InputHandler {

    private AbstractEntity ae;
    private boolean enabled = false;

    private Map map;

    public InputHandler(AbstractEntity ae, Map map) {
        this.map = map;
        this.ae = ae;
    }

    public void handle(Input i) {
        if(!enabled) return;
        com.jquest.data.Character c = (com.jquest.data.Character) ae;
        if(i.isKeyDown(Input.KEY_DOWN)) {
            c.setAnimation("WALK_DOWN");
            c.getAnimation().start();
            if(checkCollision('s'))
                ae.setY(ae.getY() + 1);
        }
        if(i.isKeyDown(Input.KEY_UP)) {
            c.setAnimation("WALK_UP");
            c.getAnimation().start();
            if(checkCollision('n'))
                ae.setY(ae.getY() - 1);
        }
        if(i.isKeyDown(Input.KEY_LEFT)) {
            c.setAnimation("WALK_LEFT");
            c.getAnimation().start();
            if(checkCollision('w'))
                ae.setX(ae.getX() - 1);
        }
        if(i.isKeyDown(Input.KEY_RIGHT)) {
            c.setAnimation("WALK_RIGHT");
            c.getAnimation().start();
            if(checkCollision('e'))
                ae.setX(ae.getX() + 1);
        }
        if(!i.isKeyDown(Input.KEY_DOWN) && !i.isKeyDown(Input.KEY_UP) && !i.isKeyDown(Input.KEY_LEFT) && !i.isKeyDown(Input.KEY_RIGHT))
            c.stopMove();
    }

    public boolean checkCollision(char direction) {
        com.jquest.data.Character c = (com.jquest.data.Character) ae;
        switch(direction) {
            case 'n':
                if(c.getY() <= 0) return false;
                break;
            case 's':
                if(c.getY() >= (map.getCanvasHeight() - 24)) return false;
                break;
            case 'w':
                if(c.getX() <= 0) return false;
                break;
            case 'e':
                if(c.getX() >= (map.getCanvasWidth() - 16)) return false;
                break;
            default:
                return true;
        }
        return true;
    }

    public void enable() {
        this.enabled = true;
    }

    public void disable() {
        this.enabled = false;
    }

}
